package com.mx.project.controller;

import com.mx.project.common.resp.ApiResult;
import com.mx.project.common.util.JWTService;
import com.mx.project.constants.Constants;
import com.mx.project.pojo.User;
import com.mx.project.vo.UserInfo;
import com.mx.project.services.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

@Log4j2
@Api("用户操作")
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JWTService jwtService;

    @ApiOperation("获取用户信息")
    @ResponseBody
    @GetMapping("info")
    public ApiResult<Map<String,String>> getInfo(HttpServletRequest request){
        ApiResult apiResult = new ApiResult();
        String token = request.getHeader("token");
        Integer uid = jwtService.getUserId(token);
        UserInfo user = userService.findUserInfoByUid(uid);
        try {
            Path temp = Paths.get(Constants.AVATAR_FILE_PATH);
            if (!Files.isWritable(temp)) {
                Files.createDirectories(temp);
                log.error(temp.toAbsolutePath().toString());
            }
            Path path = Paths.get(Constants.AVATAR_FILE_PATH + user.getAvatar());
            byte[] bytes = Files.readAllBytes(path);
            String avatar = Base64.getEncoder().encodeToString(bytes);
            user.setAvatar("data:image/"+user.getAvatar().substring(user.getAvatar().indexOf(".")+1)+";base64,"+avatar);
        } catch (IOException e) {
            log.error("avatar 转换失败!"+e.getCause());
        }
        apiResult.setData(user);
        return apiResult;
    }

    @ApiOperation("更新用户头像")
    @PostMapping("avatar")
    public ApiResult updateAvatar(HttpServletRequest request, @RequestParam("avatar") MultipartFile file){
        ApiResult apiResult = new ApiResult();
//        System.out.println(file.getName());
        String token = request.getHeader("token");
        Integer uid = jwtService.getUserId(token);
        if (file == null) {//判断非空
            return new ApiResult(400,"文件为空");
        }
        try {
//            byte[] bytes = file.getBytes();
            //要存入本地的地址放到path里面
            Path path = Paths.get(Constants.AVATAR_FILE_PATH);
            String extension = getFileExtension(file);  //获取文件后缀
//            UUID uuid = UUID.randomUUID();  //这里调用了UUID，得到全宇宙唯一的命名
//            String str = uuid.toString(); // 真正的UUID打印出来是这样的：xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (8-4-4-4-12)
            //所以我们可以去掉去掉"-"符号
//            String picname = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) +   str.substring(19, 23) + str.substring(24);
            String relativeAddr = uid  + extension;  //唯一的名字接上后缀
            File nativeFile = new File(path+"/" + relativeAddr);
            if(nativeFile.exists()){
                nativeFile.delete();
            }
            //如果没有files文件夹，则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(path);
            }
            Thumbnails.of(file.getInputStream()).size(200, 200)    //写入
                    .outputQuality(0.8f).toFile(nativeFile);
            userService.updateAvatarByUid(uid,relativeAddr);
        } catch (IOException e) {
            log.error(e.getCause());
            return new ApiResult(400,"图片上传异常");
        }
        return apiResult;
    }

    private static String getFileExtension(MultipartFile File) {
        String originalFileName = File.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));

    }

    @ApiOperation("更新用户信息")
    @PostMapping("address")
    public ApiResult updateAvatar(@RequestBody User user,HttpServletRequest request){
        ApiResult apiResult = new ApiResult();
        String token = request.getHeader("token");
        Integer uid = jwtService.getUserId(token);
        user.setUid(uid);
        userService.updateUserInfo(user);
        return apiResult;
    }

}
